package com.example.supermarket_back.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    //IdUtil.simpleUUID()
    private static String SIGNATURE = "zyf123465";

    /**
     * 生成token
     * @param map //传入payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        //等效 map.forEach((k,v)->{builder.withClaim(k,v);});
        map.forEach(builder::withClaim);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,7);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();
    }

    /**
     * 验证token
     * @param token
     */
    public static boolean verify(String token){
        boolean isTokenValid = false;
        try {
            JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
            isTokenValid = true;
        } catch (JWTVerificationException e) {
            // Token verification failed
        }
        return isTokenValid;
    }

    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    public static String getInfo(String token,String key){
        return  getToken(token).getClaim(key).asString();
    }
}
